package com.luo.backend.service;

import com.luo.backend.dto.OrderResponse;
import com.luo.backend.entity.Order;
import com.luo.backend.entity.OrderItem;
import com.luo.backend.entity.User;
import com.luo.backend.repository.OrderItemRepository;
import com.luo.backend.repository.OrderRepository;
import com.luo.backend.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 管理员订单服务类
 */
@Service
public class AdminOrderService {
    
    private static final Logger logger = LoggerFactory.getLogger(AdminOrderService.class);
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private OrderItemRepository orderItemRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    /**
     * 获取订单列表（支持分页、筛选、搜索、排序）
     */
    public Map<String, Object> getOrderList(Integer page, Integer size, String status, 
                                           String keyword, String startDate, String endDate,
                                           String sortBy, String sortOrder) {
        logger.info("管理员获取订单列表 - page: {}, size: {}, status: {}, keyword: {}", 
                   page, size, status, keyword);
        
        // 构建动态查询条件
        Specification<Order> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            
            // 状态筛选
            if (status != null && !status.trim().isEmpty()) {
                predicates.add(criteriaBuilder.equal(root.get("status"), status));
            }
            
            // 关键词搜索（订单号/用户/商家）
            if (keyword != null && !keyword.trim().isEmpty()) {
                String likePattern = "%" + keyword + "%";
                Predicate orderNoPredicate = criteriaBuilder.like(root.get("orderNo"), likePattern);
                Predicate merchantNamePredicate = criteriaBuilder.like(root.get("merchantName"), likePattern);
                Predicate deliveryNamePredicate = criteriaBuilder.like(root.get("deliveryName"), likePattern);
                
                predicates.add(criteriaBuilder.or(orderNoPredicate, merchantNamePredicate, deliveryNamePredicate));
            }
            
            // 日期范围筛选
            if (startDate != null && !startDate.trim().isEmpty()) {
                LocalDateTime startDateTime = LocalDate.parse(startDate).atStartOfDay();
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createdAt"), startDateTime));
            }
            
            if (endDate != null && !endDate.trim().isEmpty()) {
                LocalDateTime endDateTime = LocalDate.parse(endDate).atTime(LocalTime.MAX);
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createdAt"), endDateTime));
            }
            
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
        
        // 构建排序
        Sort sort;
        if (sortBy != null && !sortBy.trim().isEmpty()) {
            Sort.Direction direction = "asc".equalsIgnoreCase(sortOrder) ? 
                Sort.Direction.ASC : Sort.Direction.DESC;
            sort = Sort.by(direction, sortBy);
        } else {
            // 默认按创建时间倒序
            sort = Sort.by(Sort.Direction.DESC, "createdAt");
        }
        
        // 分页查询
        Pageable pageable = PageRequest.of(page - 1, size, sort);
        Page<Order> orderPage = orderRepository.findAll(spec, pageable);
        
        // 转换为响应DTO
        List<OrderResponse> orders = orderPage.getContent().stream()
            .map(order -> {
                OrderResponse response = new OrderResponse(order);
                // 获取订单商品明细
                List<OrderItem> items = orderItemRepository.findByOrderIdOrderByCreatedAtAsc(order.getId());
                response.setItems(items.stream()
                    .map(OrderResponse.OrderItemResponse::new)
                    .collect(Collectors.toList()));
                
                // 获取用户信息
                Optional<User> userOpt = userRepository.findById(order.getUserId());
                if (userOpt.isPresent()) {
                    response.setUsername(userOpt.get().getUsername());
                }
                
                return response;
            })
            .collect(Collectors.toList());
        
        // 构建响应
        Map<String, Object> result = new HashMap<>();
        result.put("items", orders);
        result.put("total", orderPage.getTotalElements());
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", orderPage.getTotalPages());
        
        return result;
    }
    
    /**
     * 获取订单详情
     */
    public OrderResponse getOrderDetail(Long orderId) {
        logger.info("管理员获取订单详情 - orderId: {}", orderId);
        
        Optional<Order> orderOpt = orderRepository.findById(orderId);
        if (!orderOpt.isPresent()) {
            throw new RuntimeException("订单不存在");
        }
        
        Order order = orderOpt.get();
        OrderResponse response = new OrderResponse(order);
        
        // 获取订单商品明细
        List<OrderItem> items = orderItemRepository.findByOrderIdOrderByCreatedAtAsc(order.getId());
        response.setItems(items.stream()
            .map(OrderResponse.OrderItemResponse::new)
            .collect(Collectors.toList()));
        
        // 获取用户信息
        Optional<User> userOpt = userRepository.findById(order.getUserId());
        if (userOpt.isPresent()) {
            response.setUsername(userOpt.get().getUsername());
        }
        
        return response;
    }
    
    /**
     * 删除订单（仅允许删除已取消或已退款的订单）
     */
    @Transactional
    public void deleteOrder(Long orderId) {
        logger.info("管理员删除订单 - orderId: {}", orderId);
        
        Optional<Order> orderOpt = orderRepository.findById(orderId);
        if (!orderOpt.isPresent()) {
            throw new RuntimeException("订单不存在");
        }
        
        Order order = orderOpt.get();
        
        // ⚠️ 重要：只能删除已取消或已退款的订单
        if (!"cancelled".equals(order.getStatus()) && !"refunded".equals(order.getStatus())) {
            throw new RuntimeException("只能删除已取消或已退款的订单");
        }
        
        // 删除订单（会级联删除订单商品明细）
        orderRepository.delete(order);
        
        logger.info("✅ 订单删除成功 - orderId: {}, orderNo: {}", orderId, order.getOrderNo());
    }
    
    /**
     * 修改订单状态
     */
    @Transactional
    public void updateOrderStatus(Long orderId, String newStatus, String reason) {
        logger.info("管理员修改订单状态 - orderId: {}, newStatus: {}, reason: {}", 
                   orderId, newStatus, reason);
        
        Optional<Order> orderOpt = orderRepository.findById(orderId);
        if (!orderOpt.isPresent()) {
            throw new RuntimeException("订单不存在");
        }
        
        Order order = orderOpt.get();
        String oldStatus = order.getStatus();
        
        // 更新订单状态
        order.setStatus(newStatus);
        
        // 根据新状态更新相关时间字段
        LocalDateTime now = LocalDateTime.now();
        switch (newStatus) {
            case "paid":
                if (order.getPaidAt() == null) {
                    order.setPaidAt(now);
                }
                break;
            case "preparing":
                if (order.getAcceptedAt() == null) {
                    order.setAcceptedAt(now);
                }
                break;
            case "shipping":
                if (order.getShippedAt() == null) {
                    order.setShippedAt(now);
                }
                break;
            case "delivered":
                if (order.getDeliveredAt() == null) {
                    order.setDeliveredAt(now);
                }
                break;
            case "cancelled":
                if (order.getCancelledAt() == null) {
                    order.setCancelledAt(now);
                }
                if (order.getCancelReason() == null || order.getCancelReason().isEmpty()) {
                    order.setCancelReason(reason);
                }
                break;
            case "refunded":
                if (order.getRefundedAt() == null) {
                    order.setRefundedAt(now);
                }
                if (order.getRefundReason() == null || order.getRefundReason().isEmpty()) {
                    order.setRefundReason(reason);
                }
                break;
        }
        
        order.setUpdatedAt(now);
        orderRepository.save(order);
        
        logger.info("✅ 订单状态修改成功 - orderId: {}, {} -> {}, reason: {}", 
                   orderId, oldStatus, newStatus, reason);
    }
    
    /**
     * 获取订单统计
     */
    public Map<String, Object> getOrderStatistics(String startDate, String endDate) {
        logger.info("管理员获取订单统计 - startDate: {}, endDate: {}", startDate, endDate);
        
        // 构建查询条件
        Specification<Order> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            
            // 日期范围筛选
            if (startDate != null && !startDate.trim().isEmpty()) {
                LocalDateTime startDateTime = LocalDate.parse(startDate).atStartOfDay();
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createdAt"), startDateTime));
            }
            
            if (endDate != null && !endDate.trim().isEmpty()) {
                LocalDateTime endDateTime = LocalDate.parse(endDate).atTime(LocalTime.MAX);
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createdAt"), endDateTime));
            }
            
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
        
        // 获取所有订单
        List<Order> orders = orderRepository.findAll(spec);
        
        // 总订单数
        long totalOrders = orders.size();
        
        // 总金额（只统计已支付及以后状态的订单）
        BigDecimal totalAmount = orders.stream()
            .filter(o -> !"pending".equals(o.getStatus()) && !"cancelled".equals(o.getStatus()))
            .map(Order::getTotalAmount)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        // 今日订单数
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
        LocalDateTime todayEnd = LocalDate.now().atTime(LocalTime.MAX);
        long todayOrders = orders.stream()
            .filter(o -> o.getCreatedAt().isAfter(todayStart) && o.getCreatedAt().isBefore(todayEnd))
            .count();
        
        // 平均订单金额
        BigDecimal averageAmount = totalOrders > 0 ? 
            totalAmount.divide(BigDecimal.valueOf(totalOrders), 2, RoundingMode.HALF_UP) : 
            BigDecimal.ZERO;
        
        // 各状态订单数统计
        Map<String, Long> statusCounts = orders.stream()
            .collect(Collectors.groupingBy(Order::getStatus, Collectors.counting()));
        
        // 构建响应
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalOrders", totalOrders);
        statistics.put("totalAmount", totalAmount);
        statistics.put("todayOrders", todayOrders);
        statistics.put("averageAmount", averageAmount);
        statistics.put("statusCounts", statusCounts);
        
        logger.info("订单统计完成 - totalOrders: {}, totalAmount: {}", totalOrders, totalAmount);
        
        return statistics;
    }
}

